package com.ruoyi.web.controller.ly;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


@RestController
@RequestMapping("/test/image")
@Slf4j
public class ImageTest {

    @PostMapping("/multipartFile")
    public AjaxResult multipartFile(MultipartFile file){
        log.info("当前文件的名称为：" + file.getOriginalFilename());
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 获取文件的字节
            byte[] bytes = file.getBytes();
            // 获取文件扩展名
            String extension = fileName.substring(fileName.lastIndexOf("."));
            // 使用UUID生成新的文件名
            String newFileName = IdUtil.simpleUUID() + extension;
            // 文件存储路径
            // 根据操作系统设置存储路径
            String os = System.getProperty("os.name").toLowerCase();
            String baseDir;
            if (os.contains("win")) {
                baseDir = "D:" + File.separator + "temp" + File.separator + "img";
                File tempFile = new File(baseDir);
                if (!tempFile.exists()){
                    baseDir = "C:" + File.separator + "temp" + File.separator + "img";
                }
            } else {
                baseDir = File.separator + "work" + File.separator + "img";
            }
            // 完整的文件路径
            String filePath = baseDir + File.separator + newFileName;
            // 创建目录
            File folder = new File(baseDir);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            // 创建文件
            File imageFile = new File(filePath);
            // 写入文件
            try (FileOutputStream fos = new FileOutputStream(imageFile)) {
                fos.write(bytes);
            }
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("code", HttpStatus.SUCCESS);
            ajaxResult.put("msg","上传成功");
            ajaxResult.put("name",newFileName);
            // 返回成功消息
            return ajaxResult;
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败");
        }

    }
}
